<script setup>
import { onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { showToast } from 'vant'
import { followAuthor, articleData, commentsData, recTheSame, likeAndCollection, unfollowAuthor, userLike, cancelLike, collectTravel, cancelCollection, commentTravel, commentsDelete } from '@/apis/apis.js'
import Waterfall from '@/components/common/Waterfall.vue'
import useUserStore from '@/stores/useUserStore.js'
import emitter from '@/utils/mitt.js'

emitter.on('toAnotherDetailView', async (payload) => {
  pageComments.value = 1
  commentsMore.value = true
  commentMoreText.value = true
  pageRecommends.value = 1
  recommendsMore.value = true
  recommendMoreText.value = true
  show.value = false
  await loadData(payload.id)
})

const userTravelsList = ref([])
const show = ref(false)
const route = useRoute()
const router = useRouter()
const article = ref({})
const pageComments = ref(1)
const pageRecommends = ref(1)
const comments = ref([])
const commentsMore = ref(true)
const recommendsMore = ref(true)
const userStore = useUserStore()
const isConcern = ref(false)
const commentContent = ref('')
const commentMoreText = ref(true)
const recommendMoreText = ref(true)

const loadData = async (id) => {
  let res = await articleData({ article_id: id })
  article.value = res.data[0]
  bottomData.value[0].text = article.value.likes
  bottomData.value[1].text = article.value.comments
  bottomData.value[2].text = article.value.collections

  res = await commentsData({ article_id: id, page: pageComments.value })
  comments.value = res.data
  if (res.data.length < 5) {
    commentsMore.value = false
  }

  res = await recTheSame({ article_id: id, page: pageRecommends.value })
  userTravelsList.value = res.data
  if (userTravelsList.value.length < 6) {
    recommendsMore.value = false
  }

  res = await likeAndCollection({ article_id: id, im_concerned_uid: article.value.author[0].uid })
  if (res.error !== '202') {
    bottomData.value[0].status = res.data.like
    bottomData.value[2].status = res.data.collection
    isConcern.value = res.data.concern
  }
}

onMounted(async () => {
  await loadData(route.query.article_id)
})

const concernAuthor = async () => {
  // 未关注
  if (!isConcern.value) {
    await followAuthor({ im_concerned_uid: article.value.author[0].uid })
  }
  // 已关注
  else {
    await unfollowAuthor({ im_concerned_uid: article.value.author[0].uid })
  }
  isConcern.value = !isConcern.value
}

const likeCommentCollect = async (index) => {
  // 点赞
  if (index === 0) {
    // 取消点赞
    if (bottomData.value[index].status) {
      await cancelLike({ article_id: article.value._id })
      bottomData.value[index].text = (parseInt(bottomData.value[index].text) - 1).toString()
    }
    // 点赞
    else {
      await userLike({ article_id: article.value._id })
      bottomData.value[index].text = (parseInt(bottomData.value[index].text) + 1).toString()
    }
    bottomData.value[index].status = !bottomData.value[index].status
  }
  // 评论
  else if (index === 1) {
    show.value = true
  }
  // 收藏
  else {
    // 取消收藏
    if (bottomData.value[index].status) {
      await cancelCollection({ article_id: article.value._id })
      bottomData.value[index].text = (parseInt(bottomData.value[index].text) - 1).toString()
    }
    // 收藏
    else {
      await collectTravel({ article_id: article.value._id })
      bottomData.value[index].text = (parseInt(bottomData.value[index].text) + 1).toString()
    }
    bottomData.value[index].status = !bottomData.value[index].status
  }
}

const submitComment = async () => {
  if (commentContent.value === '') {
    return showToast({ message: '评论内容不能为空', duration: 500 })
  }
  const res = await commentTravel({ article_id: article.value._id, comment_content: commentContent.value })
  comments.value.unshift(res.data)
  show.value = false
}

const deleteComment = async (item) => {
  await commentsDelete({ comment_id: item._id })
  comments.value = comments.value.filter(value => value._id !== item._id)
}

const getMoreComments = async () => {
  if (!commentMoreText.value) return
  pageComments.value++
  const res = await commentsData({ article_id: article.value._id, page: pageComments.value })
  if (res.data.length <= 0) {
    commentMoreText.value = false
  }
  comments.value = [...comments.value, ...res.data]
}

const getMoreRecommends = async () => {
  if (!recommendMoreText.value) return
  pageRecommends.value++
  const res = await recTheSame({ article_id: article.value._id, page: pageRecommends.value })
  if (res.data.length <= 0) {
    recommendMoreText.value = false
  }
  userTravelsList.value = [...userTravelsList.value, ...res.data]
}

const bottomData = ref([
  {
    text: '0',
    status: false,
    icon: 'good-job-o',
    activeIcon: 'good-job',
    color: 'red'
  },
  {
    text: '0',
    status: false,
    icon: 'comment-o',
    activeIcon: 'comment-o',
    color: ''
  },
  {
    text: '0',
    status: false,
    icon: 'like-o',
    activeIcon: 'like',
    color: 'orange'
  }
])
</script>

<template>
  <van-swipe :autoplay="2000" lazy-render>
    <van-swipe-item v-for="(item, index) in article.image" :key="index">
      <van-image fit="cover" :src="item" />
    </van-swipe-item>
    <template #indicator="{ active, total }">
      <div class="custom-indicator">{{ active + 1 }}/{{ total }}</div>
    </template>
  </van-swipe>
  <div class="user" v-if="JSON.stringify(article) !== '{}'">
    <div class="left">
      <van-image width="1rem" height="1rem" round fit="cover" :src="article.author[0].avatarUrl" />
      <div class="info">
        <span class="name">{{ article.author[0].nickname }}</span>
        <span class="publish">{{ article.time }}发布</span>
      </div>
    </div>
    <div class="right">
      <van-button type="warning" size="small" @click="concernAuthor">{{ isConcern ? '已关注' : '+ 关注' }}</van-button>
    </div>
  </div>
  <div class="article">
    <div class="article-title">{{ article.title }}</div>
    <div class="article-content">{{ article.content }}</div>
  </div>
  <div class="comments" v-show="comments.length > 0">
    <div class="comment" v-for="item in comments" :key="item._id">
      <van-image width="0.8rem" height="0.8rem" round fit="cover" :src="item.comment_user[0].avatarUrl" />
      <div class="comment-user">
        <div class="comment-name">
          <span>{{ item.comment_user[0].nickname }}</span>
          <span style="color: red;" v-if="item.user_uid === userStore.user.uid" @click="deleteComment(item)">删除</span>
        </div>
        <div class="comment-content">{{ item.content }}</div>
      </div>
    </div>
    <div class="more" v-if="commentsMore" @click="getMoreComments">{{ commentMoreText ? '查看更多' : '没有更多了' }}</div>
  </div>
  <div class="recommend" v-show="userTravelsList.length > 0">
    <div class="recommend-title">相关推荐</div>
    <div class="recommend-body">
      <Waterfall :userTravelsList="userTravelsList" />
    </div>
    <div class="more" v-if="recommendsMore" @click="getMoreRecommends">{{ recommendMoreText ? '查看更多' : '没有更多了' }}</div>
  </div>
  <div class="ghost"></div>
  <div class="bottom-container" style="position: fixed; bottom: 0; left: 0; right: 0;">
    <div class="bottom-left">
      <div class="input" @click="show = true">谈谈感受</div>
    </div>
    <div class="bottom-right">
      <div class="bottom-right-item" v-for="(item, index) in bottomData" :key="index" @click="likeCommentCollect(index)">
        <van-icon size="0.7rem" :name="item.status ? item.activeIcon : item.icon"
          :color="item.status ? item.color : ''" />
        <span>{{ item.text }}</span>
      </div>
    </div>
  </div>
  <van-popup position="top" v-model:show="show" :close-on-click-overlay="false" @close="commentContent = ''">
    <template #default>
      <textarea v-model="commentContent" name="" id="" placeholder="请输入评论"></textarea>
    </template>
    <template #overlay-content>
      <div style="display: flex; justify-content: flex-end;">
        <van-button @click="show = false">取消</van-button>
        <van-button type="success" @click="submitComment">发表</van-button>
      </div>
    </template>
  </van-popup>
</template>

<style scoped lang="scss">
.van-overlay {
  padding: 0 10px;
  padding-top: 250px;

  .van-button {
    width: 70px;
    height: 30px;

    &:first-child {
      margin-right: 20px;
    }
  }
}

.van-popup {
  padding: 15px;

  textarea {
    width: 100%;
    height: 200px;
    border: none;
    outline: none;
    font-size: 16px;
  }
}

.van-swipe {
  height: 300px;
}

.van-image {
  width: 100%;
  height: 100%;
}

.custom-indicator {
  position: absolute;
  right: 5px;
  bottom: 5px;
  padding: 2px 5px;
  background: rgba(0, 0, 0, 0.1);
  font-size: 12px;
}

.user {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 10px;
  padding: 10px;
  box-shadow: rgba(99, 99, 99, 0.2) 0px 2px 8px 0px;

  .left {
    display: flex;
    align-items: center;

    .info {
      display: flex;
      flex-direction: column;
      margin-left: 10px;

      .name {
        font-size: 18px;
      }

      .publish {
        font-size: 14px;
      }
    }
  }

  .right {
    display: flex;
  }
}

.article {
  padding: 20px 10px;

  .article-title {
    margin-bottom: 20px;
    font-weight: bold;
    font-size: 20px;
  }

  .article-content {
    font-size: 18px;
  }
}

.comments {
  padding: 10px;

  .comment {
    display: flex;
    padding: 20px 10px;
    background-color: #f8fafb;

    .comment-user {
      width: 290px;
      margin-left: 10px;

      .comment-name {
        display: flex;
        justify-content: space-between;
        margin-bottom: 5px;
        color: #ccc;
        font-size: 18px;
      }

      .comment-content {
        word-wrap: break-word;
        overflow-wrap: break-word;
        font-size: 18px;
      }
    }
  }

  .more {
    padding: 10px 0;
    background-color: #f8fafb;
    text-align: center;
    color: rgb(11, 177, 237);
    font-size: 14px;
  }
}

.recommend {

  .recommend-title {
    margin: 0 10px;
    margin-bottom: 20px;
    font-size: 18px;
    font-weight: bold;
  }

  .more {
    padding: 10px 0;
    text-align: center;
    color: rgb(11, 177, 237);
    font-size: 14px;
  }
}

.bottom-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background-color: white;
  border-top: 1px solid #eee;

  .bottom-left {
    display: flex;
    width: 200px;
    height: 40px;

    .input {
      padding: 0 10px;
      width: 100%;
      background-color: #f4f9fa;
      line-height: 40px;
      border: none;
      border-radius: 20px;
      outline: none;
      font-size: 16px;
    }
  }

  .bottom-right {
    display: flex;
    flex: 1;
    justify-content: space-around;
    align-items: center;
    margin-left: 10px;

    .bottom-right-item {
      display: flex;
      flex-direction: column;
      align-items: center;

      span {
        margin-top: 3px;
        color: #aaa;
        font-size: 16px;
      }
    }
  }
}

.ghost {
  height: 100px;
}
</style>
